package org.microsites.domain.dao.eod;

import java.util.ArrayList;
import java.util.List;

import net.lemnik.eodsql.BaseQuery;
import net.lemnik.eodsql.DataSet;
import net.lemnik.eodsql.GeneratedKeys;
import net.lemnik.eodsql.Select;
import net.lemnik.eodsql.Update;

import org.microsites.domain.dao.UserDAO;
import org.microsites.domain.model.User;
import org.microsites.util.EodDaoSupport;

public class UserDAOImpl extends EodDaoSupport implements UserDAO {
	private Query query;
	
	@Override
	public void create(User entity) {
		entity.setId(getQuery().create(entity));
	}

	@Override
	public void delete(Long id) {
		getQuery().delete(id);
	}

	@Override
	public List<User> list() {
		return getQuery().list();
	}

	@Override
	public List<User> sublist(Long id) {
		return new ArrayList<User>();
	}

	@Override
	public User load(Long id) {
		return getQuery().load(id);
	}

	@Override
	public void update(User entity) {
		getQuery().update(entity);
	}
	
	public Query getQuery() {
		return query == null ? query = super.getQuery(Query.class) : query;
	}

    @Override
	public User login(String uid, String pwd) {
		return getQuery().login(uid, pwd);
	}

	@Override
	public List<String> autocomplete(String column, String pattern) {
		return super.select(String.class, "SELECT " + column + " FROM [User] WHERE " + column + " LIKE ?1 GROUP BY " + column, '%' + pattern + '%');
	}

	static interface Query extends BaseQuery {
		
		@Select(sql = "SELECT * FROM [User] WHERE uid=?1 AND pwd=?2")
		public User login(String uid, String pwd);
		
        @Update(sql = "INSERT INTO [User] (name,description,domain,uid,pwd) VALUES (?{1.name},?{1.description},?{1.domain},?{1.uid},?{1.pwd})",
                keys = GeneratedKeys.RETURNED_KEYS_FIRST_COLUMN)
		public Long create(User u);
		
        @Update(sql = "UPDATE [User] SET name=?{1.name},description=?{1.description},uid=?{1.uid},pwd=?{1.pwd},domain=?{1.domain} WHERE id=?{1.id}")
		public void update(User u);
		
        @Update(sql = "DELETE FROM [User] WHERE id=?1")
		public void delete(Long id);
		
        @Select(sql = "SELECT * FROM [User]")
        public DataSet<User> list();

		@Select(sql = "SELECT * FROM [User] WHERE id=?1")
		public User load(Long id);
	}

}
